package com.zzyl.oss.config;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.SetBucketLoggingRequest;
import com.zzyl.oss.properties.AliOssConfigProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class OssAliyunAutoConfig {

    @Autowired
    AliOssConfigProperties aliOssConfigProperties;

    @Bean
    public OSS ossClient(){
        log.info("-----------------开始创建OSSClient--------------------");
        OSS ossClient = new OSSClientBuilder().build(aliOssConfigProperties.getEndpoint(),
                aliOssConfigProperties.getAccessKeyId(), aliOssConfigProperties.getAccessKeySecret());
        
        try {
            //判断容器是否存在,不存在就创建
            if (!ossClient.doesBucketExist(aliOssConfigProperties.getBucketName())) {
                log.info("Bucket {} 不存在，尝试创建", aliOssConfigProperties.getBucketName());
                ossClient.createBucket(aliOssConfigProperties.getBucketName());
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(aliOssConfigProperties.getBucketName());
                //设置问公共可读
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                ossClient.createBucket(createBucketRequest);
                log.info("Bucket {} 创建成功", aliOssConfigProperties.getBucketName());
            }
        } catch (Exception e) {
            log.warn("检查或创建 Bucket {} 时出现异常: {}", aliOssConfigProperties.getBucketName(), e.getMessage());
        }

        try {
            //添加客户端访问日志
            SetBucketLoggingRequest request = new SetBucketLoggingRequest(aliOssConfigProperties.getBucketName());
            // 设置存放日志文件的存储空间。
            request.setTargetBucket(aliOssConfigProperties.getBucketName());
            // 设置日志文件存放的目录。
            request.setTargetPrefix(aliOssConfigProperties.getBucketName());
            ossClient.setBucketLogging(request);
            log.info("Bucket {} 日志配置设置成功", aliOssConfigProperties.getBucketName());
        } catch (Exception e) {
            log.warn("设置 Bucket {} 日志配置时出现异常: {}", aliOssConfigProperties.getBucketName(), e.getMessage());
            log.warn("这可能是由于权限不足导致的，但不影响 OSS 客户端的基本功能");
        }

        log.info("-----------------结束创建OSSClient--------------------");
        return ossClient;
    }
}
